package com.hnust.controller.paper.component;

import com.hnust.fx.FXMLController;
import com.hnust.service.TestPaperService;
import com.hnust.store.PaperListDataStore;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import okhttp3.ResponseBody;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.UUID;

@FXMLController
public class PreviewPaperController implements Initializable{
    @Autowired
    private TestPaperService testPaperService;
    @Autowired
    private PaperListDataStore paperListDataStore;
    @FXML
    public AnchorPane container;
    @FXML
    public HBox imageContain;
    @FXML
    public ScrollPane inImageContain;
    @FXML
    public ImageView paperImageView;
    @FXML
    public Button downloadBtn;
    @FXML
    public Button downloadAnswerBtn;
    @FXML
    public Button downloadPlanBtn;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        container.parentProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
//                downloadBtn.setVisible(false);
//                downloadAnswerBtn.setVisible(false);
//                downloadPlanBtn.setVisible(false);
                loading();
                getPaperpic();
            }else{
                clear();
            }
        });
    }
    //页面关闭，清空数据
    public void clear(){
        paperImageView.setFitWidth(0);
        paperImageView.setImage(null);
        downloadBtn.setVisible(false);
        downloadAnswerBtn.setVisible(false);
        downloadPlanBtn.setVisible(false);
    }
    //Loading图片
    public void loading(){
        InputStream in=null;
        try{
            in=new FileInputStream("src/main/resources/image/loading.png");
            Image image=new Image(in);
            double pW=image.getWidth();
            paperImageView.setFitWidth(pW*2);
            paperImageView.setPreserveRatio(true);
            paperImageView.setImage(image);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                in.close();
            }catch (Exception e){

            }

        }


    }
    //获取图片
    public void getPaperpic(){
        testPaperService.getPaperpic(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            InputStream in=response.body().byteStream();
                            setPdfToImageByStream(in);
                            in.close();
                            downloadBtn.setVisible(true);
                            downloadAnswerBtn.setVisible(true);
                            downloadPlanBtn.setVisible(true);
                        }catch (Exception e){

                        }
                    }
                });
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                        alert.showAndWait();
                    }
                });

            }
        },paperListDataStore.getPaper_id());
    }
    //下载试卷
    public void download(){
        testPaperService.getPaperdocx(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        InputStream in=response.body().byteStream();
                        FileOutputStream os=null;
                        try{
                            DirectoryChooser directoryChooser=new DirectoryChooser();
                            File file1 = directoryChooser.showDialog(null);
                            if(file1==null){
                                throw new Exception("空指针异常！");
                            }
                            String path = file1.getPath();//选择的文件夹路径
                            String name= UUID.randomUUID().toString().replaceAll("-","").substring(0,7)+"试卷";
                            os = new FileOutputStream(path+"\\"+name+".docx");
                            byte[] buffer = new byte[4 * 1024];
                            int read;
                            while ((read = in.read(buffer)) > 0) {
                                os.write(buffer, 0, read);
                            }
                        }catch (Exception e){

                        }finally {
                            try{
                                os.close();
                                in.close();
                            }catch (Exception e){

                            }
                        }
                    }
                });
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                        alert.showAndWait();
                    }
                });
            }
        },paperListDataStore.getPaper_id());
    }

    //通过PDF输入流，将PDF转成图片
    public void setPdfToImageByStream(InputStream in){
        try {
            PDDocument doc = PDDocument.load(in);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pW = (int) doc.getPage(0).getMediaBox().getWidth();
            int pH = (int) doc.getPage(0).getMediaBox().getHeight();
            int count=doc.getNumberOfPages();
            BufferedImage tag = new BufferedImage(pW, pH*count, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.createGraphics();
            for (int i = 0; i < count; i++) {
                BufferedImage image = renderer.renderImage(i);
                g.drawImage(image, 0, pH * i, pW, pH, null);
            }
            Image image1 = SwingFXUtils.toFXImage(tag, null);
            paperImageView.setFitWidth(pW);
            paperImageView.setPreserveRatio(true);
            paperImageView.setSmooth(true);
            paperImageView.setCache(true);
            paperImageView.setImage(image1);
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //下载试卷答案
    public void downloadAnswer(){
        testPaperService.getPaperAnswerdocx(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        InputStream in=response.body().byteStream();
                        FileOutputStream os=null;
                        try{
                            DirectoryChooser directoryChooser=new DirectoryChooser();
                            File file1 = directoryChooser.showDialog(null);
                            if(file1==null){
                                throw new Exception("空指针异常！");
                            }
                            String path = file1.getPath();//选择的文件夹路径
                            String name= UUID.randomUUID().toString().replaceAll("-","").substring(0,7)+"答案";
                            os = new FileOutputStream(path+"\\"+name+".docx");
                            byte[] buffer = new byte[4 * 1024];
                            int read;
                            while ((read = in.read(buffer)) > 0) {
                                os.write(buffer, 0, read);
                            }
                        }catch (Exception e){

                        }finally {
                            try{
                                os.close();
                                in.close();
                            }catch (Exception e){

                            }
                        }
                    }
                });
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                        alert.showAndWait();
                    }
                });
            }
        },paperListDataStore.getPaper_id());
    }
    //下载命题计划表
    public void downloadPlan(){
        testPaperService.getPaperPlandocx(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        InputStream in=response.body().byteStream();
                        FileOutputStream os=null;
                        try{
                            DirectoryChooser directoryChooser=new DirectoryChooser();
                            File file1 = directoryChooser.showDialog(null);
                            if(file1==null){
                                throw new Exception("空指针异常！");
                            }
                            String path = file1.getPath();//选择的文件夹路径
                            String name= UUID.randomUUID().toString().replaceAll("-","").substring(0,7)+"命题计划表";
                            os = new FileOutputStream(path+"\\"+name+".docx");
                            byte[] buffer = new byte[4 * 1024];
                            int read;
                            while ((read = in.read(buffer)) > 0) {
                                os.write(buffer, 0, read);
                            }
                        }catch (Exception e){

                        }finally {
                            try{
                                os.close();
                                in.close();
                            }catch (Exception e){

                            }
                        }
                    }
                });
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                        alert.showAndWait();
                    }
                });
            }
        },paperListDataStore.getPaper_id());
    }
}
